package com.gitee.apanlh.util.sensitive;

import com.gitee.apanlh.annotation.sensitive.SensitiveItemType;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.base.builder.MapBuilder;
import com.gitee.apanlh.util.reflection.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Map;

/**	
 * 	脱敏注解识别
 * 	
 * 	@author Pan
 */
public class SensitiveData {
	
	/**
	 * 	存放可供选择的脱敏项类型
	 * 	<br>key 	为 枚举
	 * 	<br>value 	为	脱敏编号
	 * 	<br>具体可参照安全脱敏规则
	 */
	protected static final Map<SensitiveItemEnum, String> SENSITIVE_ITEM_TYPE = new MapBuilder.Builder<SensitiveItemEnum, String>(16)
		.put(SensitiveItemEnum.USER_NO, 		"1")
		.put(SensitiveItemEnum.USER_NAME, 		"2")
		.put(SensitiveItemEnum.USER_ADDRESS, 	"3")
		.put(SensitiveItemEnum.USER_PHONE, 		"4")
	.build();
	
	/**
	 * 	构造函数
	 * 
	 * 	@author Pan
	 */
	private SensitiveData() {
		//	不允许外部实例
		super();
	}
	
	/**		
	 * 	根据对象
	 * 	<br>扫描并获取 字段
	 *
	 * 	@author  Pan
	 * 	@param  <T>      数据类型
	 * 	@param   t 对象
	 * 	@return	 Map
	 */
	public static <T> Map<String, SensitiveItemEnum> scanAnnotation(T t) {
		//	K = 字段名、 V = 脱敏类型
		Map<String, SensitiveItemEnum> findAnnotation = MapUtils.newHashMap();
		
		Field[] fields = ReflectionUtils.getFields(t);
		for (int i = 0, len = fields.length; i < len; i++) {
			Field field = fields[i];
			//	验证是否包含此注解
			if (field.isAnnotationPresent(SensitiveItemType.class)) {
				Annotation[] annotations = field.getDeclaredAnnotations();
				//	搜索注解
				for (Annotation annotation : annotations) {
					Class<? extends Annotation> annotationType = annotation.annotationType();
					if (annotationType.equals(SensitiveItemType.class)) {
						//	存放值
						findAnnotation.put(field.getName(), field.getAnnotation(SensitiveItemType.class).type());
					}
				}
			}
		}
		return findAnnotation;
	}
}
